package com.zzhrtech.wgzx_cityzen.ui.disease;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.LatLng;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.GsonRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.zzhrtech.WgzxApplication;
import com.zzhrtech.wgzx_cityzen.BaseActivity;
import com.zzhrtech.wgzx_cityzen.Constans;
import com.zzhrtech.wgzx_cityzen.R;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateContentBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateInfoBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.CateListBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.DepartInfoBean;
import com.zzhrtech.wgzx_cityzen.beans.disease.RoleListBean;
import com.zzhrtech.wgzx_cityzen.ui.me.MonitorActivity;
import com.zzhrtech.wgzx_cityzen.utils.FileUtil;
import com.zzhrtech.wgzx_cityzen.utils.OkHttpPicManager;


import org.angmarch.views.NiceSpinner;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;


public class DiseaseUploadActivity extends BaseActivity implements OnDateSetListener, LocationSource, AMapLocationListener,VideoView {

    NiceSpinner spinner_info, spinner_content;
    //    ArrayList<Uri> image_uris = new ArrayList<Uri>();
    private ViewGroup mSelectedImagesContainer;
//    private TimePickerDialog timePickerDialog;
    private EditText tv_time, et_address, et_name, et_phone, et_note;
    private TextView et_depart, et_class;
    List<CateInfoBean.Data> cateInfoList;
    List<CateContentBean.Data> cateContentList;
    String mdepId = "", mcatId = "", mciId = "", mcisId = "", maddress;
    String mcatName;
    double mLati = 0, mLongi = 0;
    long mtimeStamp;

    TextureMapView mMapView;
    AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private final OkHttpClient client = new OkHttpClient();

    private ArrayList<String> mImages;
    private ArrayList<String> totalImages = new ArrayList<String>();

    private ImageView iv_video,iv_camera;
    private FrameLayout videoView;
    private String videoPath;

    private String mFilePath;
    private String tempPath = Environment.getExternalStorageDirectory().getPath();
    private final int CAMERA_CODE = 233;
    private String img1 = "wgzx1.png",img2 = "wgzx2.png",img3 = "wgzx3.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_disease_upload);

        mMapView = (TextureMapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
        mMapView.onCreate(savedInstanceState);
        toolbar.setNavigationIcon(R.mipmap.ic_close);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(DiseaseUploadActivity.this)
                        .content("是否放弃上传？")
                        .negativeText("取消")
                        .positiveText("确定")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                finish();
                            }
                        })
                        .show();
            }
        });

        mdepId = getIntent().getStringExtra("depid");
        mcatId = getIntent().getStringExtra("catid");
        mcatName = getIntent().getStringExtra("catname");


        initView();


        httpGetDepart();
        httpGetCateInfo(mcatId);


//        timePickerDialog = new TimePickerDialog.Builder()
//                .setType(Type.ALL)
//                .setTitleStringId("时间选择")
//                .setThemeColor(getResources().getColor(R.color.colorPrimary))
//                .setCallBack(this)
//                .build();
    }

    //初始化布局
    private void initView() {
        //初始化地图控件
        initMap();
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Intent intent = new Intent(DiseaseUploadActivity.this, DiseaseMapActivity.class);
                startActivityForResult(intent, 6);

            }
        });

        //菜单栏点击事件
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getItemId() == R.id.upload) {


//                    httpUpload(HTTP_SERVER + "Task/test");
                    if (mciId.isEmpty()) {
                        showToast("请选择问题类型");
                    } else if (et_name.getText().toString().isEmpty()) {
                        showToast("请输入姓名");
                    } else if (et_phone.getText().toString().isEmpty()) {
                        showToast("请输入电话");
                    } else if (totalImages.size() < 2){
                        showToast("选择近景及远景两张图片");
                    }else {

                        new MaterialDialog.Builder(DiseaseUploadActivity.this)
                                .title("上传")
                                .content("是否确认上传'" + et_depart.getText().toString() + "'的任务")
                                .negativeText("取消")
                                .positiveText("确定")
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        httpUpload(HTTP_TASKADD);
                                        dialog.dismiss();
                                    }
                                })
                                .show();
                    }
                }
                return true;
            }
        });

        //时间不可输入
        tv_time = (EditText) findViewById(R.id.tv_time);
        if (tv_time != null)
            tv_time.setKeyListener(null);

        et_depart = (TextView) findViewById(R.id.et_depart);
        et_class = (TextView) findViewById(R.id.et_class);

        //获得当前时间
        mtimeStamp = new Date().getTime();
        String date = DateFormat.getDateTimeInstance().format(new Date().getTime());
        tv_time.setText(date);

//        tv_time.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                timePickerDialog.show(getSupportFragmentManager(), "all");
//            }
//        });


        //初始化下啦列表
        spinner_info = (NiceSpinner) findViewById(R.id.spinner_info);
        spinner_info.setOnItemSelectedListener(selectedListener);
        spinner_content = (NiceSpinner) findViewById(R.id.spinner_content);
        spinner_content.setOnItemSelectedListener(selectedListener);
        mSelectedImagesContainer = (ViewGroup) findViewById(R.id.selected_photos_container);
        et_address = (EditText) findViewById(R.id.et_address);
        et_name = (EditText) findViewById(R.id.et_name);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_note = (EditText) findViewById(R.id.et_note);

        iv_video = (ImageView) findViewById(R.id.iv_video);
        iv_camera = (ImageView) findViewById(R.id.iv_camera);
        videoView = (FrameLayout) findViewById(R.id.videoView);

        et_class.setText(mcatName);

        et_name.setText(getCache().getAsString(keyNickname));
        et_phone.setText(getCache().getAsString(keyUsername));

        iv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (videoView.getVisibility() == View.VISIBLE){

                    new MaterialDialog.Builder(DiseaseUploadActivity.this)
                            .title("提示")
                            .content("替换上一个视频？")
                            .negativeText("取消")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    checkAudioPermission();
                                    dialog.dismiss();
                                }
                            })
                            .show();

                }else {
                    checkAudioPermission();
                }
            }
        });

        videoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(DiseaseUploadActivity.this, MonitorActivity.class);
                intent.putExtra("path", videoPath);
                startActivity(intent);

            }
        });
        //初始化相机按钮
        initCamera();
    }

    AdapterView.OnItemSelectedListener selectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (position > 0) {
                switch (parent.getId()) {

                    case R.id.spinner_info:
                        mciId = cateInfoList.get(position - 1).getCat_id();
                        httpGetCateContent(cateInfoList.get(position - 1).getCat_id());
                        break;
                    case R.id.spinner_content:
                        mcisId = cateContentList.get(position - 1).getCat_id();
                        break;

                }
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };


    private void checkPermission() {

        int finelocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int coarselocation = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);

        boolean readStoragePermissionGranted = finelocation != PackageManager.PERMISSION_GRANTED;
        boolean cameraPermissionGranted = coarselocation != PackageManager.PERMISSION_GRANTED;

        if (readStoragePermissionGranted || cameraPermissionGranted) {

            // Should we show an explanation?

            String[] permissions;
            if (readStoragePermissionGranted && cameraPermissionGranted) {
                permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION };
            } else {
                permissions = new String[] {
                        readStoragePermissionGranted ? Manifest.permission.ACCESS_FINE_LOCATION
                                : Manifest.permission.ACCESS_COARSE_LOCATION
                };
            }

            ActivityCompat.requestPermissions(this,
                    permissions,
                    123);

        } else {
            // Permission granted
            setUpMap();
        }

    }

    private void checkPhotoPermission() {

        int readstorage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        int camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);

        boolean readStoragePermissionGranted = readstorage != PackageManager.PERMISSION_GRANTED;
        boolean cameraPermissionGranted = camera != PackageManager.PERMISSION_GRANTED;

        if (readStoragePermissionGranted || cameraPermissionGranted) {

            // Should we show an explanation?
            String[] permissions;
            if (readStoragePermissionGranted && cameraPermissionGranted) {
                permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA };
            } else {
                permissions = new String[] {
                        readStoragePermissionGranted ? Manifest.permission.READ_EXTERNAL_STORAGE
                                : Manifest.permission.CAMERA
                };
            }
            ActivityCompat.requestPermissions(this,
                    permissions,
                    124);

        } else {
            // Permission granted
            if (totalImages.size() == 0) {
                mFilePath = tempPath + "/" + img1;
            }else if(totalImages.size() == 1){
                if (totalImages.get(0).endsWith(img1)) {
                    mFilePath = tempPath + "/" + img2;
                }else if (totalImages.get(0).endsWith(img2)) {
                    mFilePath = tempPath + "/" + img1;
                }else if (totalImages.get(0).endsWith(img3)) {
                    mFilePath = tempPath + "/" + img2;
                }
            }else if (totalImages.size() == 2){
                if (totalImages.get(0).endsWith(img1) && totalImages.get(1).endsWith(img2) || totalImages.get(0).endsWith(img2) && totalImages.get(1).endsWith(img1)){
                    mFilePath = tempPath + "/" + img3;
                }else if (totalImages.get(0).endsWith(img1) && totalImages.get(1).endsWith(img3) || totalImages.get(0).endsWith(img3) && totalImages.get(1).endsWith(img1)){
                    mFilePath = tempPath + "/" + img2;
                }else if (totalImages.get(0).endsWith(img2) && totalImages.get(1).endsWith(img3) || totalImages.get(0).endsWith(img3) && totalImages.get(1).endsWith(img2)){
                    mFilePath = tempPath + "/" + img1;
                }
            }


            File vFile = new File(mFilePath);
            if(!vFile.exists())
            {
                File vDirPath = vFile.getParentFile(); //new File(vFile.getParent());
                vDirPath.mkdirs();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri photoUri = Uri.fromFile(vFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, CAMERA_CODE);


//            PhotoPicker.builder()
//                    .setPhotoCount(picCount - totalImages.size())
//                    .setShowCamera(true)
//                    .setShowGif(true)
//                    .setPreviewEnabled(false)
//                    .start(DiseaseUploadActivity.this, PhotoPicker.REQUEST_CODE);
        }

    }

    private void checkAudioPermission() {

        int audio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
        int camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);

        boolean readStoragePermissionGranted = audio != PackageManager.PERMISSION_GRANTED;
        boolean cameraPermissionGranted = camera != PackageManager.PERMISSION_GRANTED;

        if (readStoragePermissionGranted || cameraPermissionGranted) {

            // Should we show an explanation?
            String[] permissions;
            if (readStoragePermissionGranted && cameraPermissionGranted) {
                permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA };
            } else {
                permissions = new String[] {
                        readStoragePermissionGranted ? Manifest.permission.RECORD_AUDIO
                                : Manifest.permission.CAMERA
                };
            }

            ActivityCompat.requestPermissions(this,
                    permissions,
                    125);

        } else {
            VideoInputDialog.show(getSupportFragmentManager());
            // Permission granted
        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

            if (requestCode == 123) {
                setUpMap();
            }else if (requestCode == 124){

                //拍照
                if (totalImages.size() == 0) {
                    mFilePath = tempPath + "/" + img1;
                }else if(totalImages.size() == 1){
                    if (totalImages.get(0).endsWith(img1)) {
                        mFilePath = tempPath + "/" + img2;
                    }else if (totalImages.get(0).endsWith(img2)) {
                        mFilePath = tempPath + "/" + img1;
                    }else if (totalImages.get(0).endsWith(img3)) {
                        mFilePath = tempPath + "/" + img2;
                    }
                }else if (totalImages.size() == 2){
                    if (totalImages.get(0).endsWith(img1) && totalImages.get(1).endsWith(img2) || totalImages.get(0).endsWith(img2) && totalImages.get(1).endsWith(img1)){
                        mFilePath = tempPath + "/" + img3;
                    }else if (totalImages.get(0).endsWith(img1) && totalImages.get(1).endsWith(img3) || totalImages.get(0).endsWith(img3) && totalImages.get(1).endsWith(img1)){
                        mFilePath = tempPath + "/" + img2;
                    }else if (totalImages.get(0).endsWith(img2) && totalImages.get(1).endsWith(img3) || totalImages.get(0).endsWith(img3) && totalImages.get(1).endsWith(img2)){
                        mFilePath = tempPath + "/" + img1;
                    }
                }


                File vFile = new File(mFilePath);
                if(!vFile.exists())
                {
                    File vDirPath = vFile.getParentFile(); //new File(vFile.getParent());
                    vDirPath.mkdirs();
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                Uri photoUri = Uri.fromFile(vFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                startActivityForResult(intent, CAMERA_CODE);
            }else if (requestCode == 125){
                showToast("重新点击视频");
            }
        }else {

        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    //初始化照相按钮
    private void initCamera() {
        View imageHolder = LayoutInflater.from(this).inflate(R.layout.item_camera, null);
        ImageView imageView = (ImageView) imageHolder.findViewById(R.id.media_image);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkPhotoPermission();

            }
        });
        mSelectedImagesContainer.addView(imageHolder);
    }


    /**
     * 初始化AMap对象
     */
    private void initMap() {
        if (aMap == null) {
            aMap = mMapView.getMap();

            checkPermission();
        }
    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        aMap.setLocationSource(this);// 设置定位监听

        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }


    private void showMedia(final List<String> images) {
        // Remove all views before
        // adding the new ones.
        mSelectedImagesContainer.removeAllViews();

        if (images.size() >= 1) {
            mSelectedImagesContainer.setVisibility(View.VISIBLE);
        }

        //dip转换为sp
        int wdpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, getResources().getDisplayMetrics());
        int htpx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 72, getResources().getDisplayMetrics());

        for (int i = 0; i < images.size(); i++) {
            View imageHolder = LayoutInflater.from(this).inflate(R.layout.item_image, null);
            ImageView thumbnail = (ImageView) imageHolder.findViewById(R.id.media_image);

            final int currentPage = i;
            thumbnail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(DiseaseUploadActivity.this, ImagePickActivity.class);
                    intent.putStringArrayListExtra("images", totalImages);
                    intent.putExtra("current", currentPage);
                    intent.putExtra("channel", "upload");
                    startActivityForResult(intent, 3);

                }
            });


            Glide.with(this)
                    .load(images.get(i))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache( true )
                    .fitCenter()
                    .into(thumbnail);

            mSelectedImagesContainer.addView(imageHolder);
            thumbnail.setLayoutParams(new FrameLayout.LayoutParams(wdpx, htpx));
        }

        if (images.size() < 3) {
            initCamera();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {

//            if (data != null) {


               Log.d("bi========",getBitmapDegree(mFilePath) + "---");

                totalImages.add(mFilePath);

                showMedia(totalImages);
//            }
        } else if (requestCode == 3 & resultCode == RESULT_OK) {
            mImages = data.getStringArrayListExtra("imglist");
            totalImages = mImages;
            showMedia(totalImages);
        } else if (requestCode == 6 & resultCode == RESULT_OK) {
            if (data.getStringExtra("address") != null) {
                et_address.setText(data.getStringExtra("address"));
                mLati = data.getDoubleExtra("lat", 0);
                mLongi = data.getDoubleExtra("long", 0);
            }
        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path
     *            图片绝对路径
     * @return 图片的旋转角度
     */
    private int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm
     *            需要旋转的图片
     * @param degree
     *            旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {

        mtimeStamp = millseconds;

        tv_time.setText(DateFormat.getDateTimeInstance().format(new Date(millseconds)));

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_disupload, menu);
        return true;
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {

        return super.onMenuOpened(featureId, menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }


    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置是否只定位一次,默认为false
            mLocationOption.setOnceLocation(true);
            //设置为高精度定位模式,Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {

        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                mLati = aMapLocation.getLatitude();//获取纬度
                mLongi = aMapLocation.getLongitude();//获取经度
                maddress = aMapLocation.getAddress();//获取地址

                CameraUpdate update = CameraUpdateFactory.zoomTo(17);
                aMap.moveCamera(update);

                update = CameraUpdateFactory.changeTilt(30);
                aMap.moveCamera(update);

                et_address.setText(maddress);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();

            }
        }
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            if (msg.what == 0) {
                DepartInfoBean.Data data = (DepartInfoBean.Data) msg.obj;
                et_depart.setText(data.getDep_name());

            } else if (msg.what == 2) {
                cateInfoList = (List<CateInfoBean.Data>) msg.obj;

                List<String> dataset = new ArrayList<String>();
                for (int i = 0; i < cateInfoList.size(); i++) {
                    dataset.add(cateInfoList.get(i).getCat_name());
                }
                spinner_info.attachDataSource(dataset);


            } else if (msg.what == 3) {
                cateContentList = (List<CateContentBean.Data>) msg.obj;
                List<String> dataset = new ArrayList<String>();
                for (int i = 0; i < cateContentList.size(); i++) {
                    dataset.add(cateContentList.get(i).getCat_name());
                }
                spinner_content.attachDataSource(dataset);

            }

            return false;
        }
    });


    private void httpGetDepart() {

        Map<String, String> params = new HashMap<String, String>();
        params.put("dep_id", mdepId);

        GsonRequest<DepartInfoBean> gsonRequest = new GsonRequest<DepartInfoBean>(com.android.volley.Request.Method.POST, Constans.HTTP_GETDEPART, DepartInfoBean.class, params, new com.android.volley.Response.Listener<DepartInfoBean>() {
            @Override
            public void onResponse(DepartInfoBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 0;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                } else {
                    showToast(response.getMsg());
                }

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====", error + "");
//                dialog.dismiss();
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private void httpGetCateInfo(String catid) {
        Log.d("id=====", catid);
        Map<String, String> params = new HashMap<String, String>();
        params.put("cat_id", catid);
        GsonRequest<CateInfoBean> gsonRequest = new GsonRequest<CateInfoBean>(com.android.volley.Request.Method.POST, Constans.HTTP_CATEINFO, CateInfoBean.class, params, new com.android.volley.Response.Listener<CateInfoBean>() {
            @Override
            public void onResponse(CateInfoBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 2;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====", error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }

    private void httpGetCateContent(String ciid) {


        Map<String, String> params = new HashMap<String, String>();
        params.put("ci_id", ciid);
        GsonRequest<CateContentBean> gsonRequest = new GsonRequest<CateContentBean>(com.android.volley.Request.Method.POST, Constans.HTTP_CATECONTENT, CateContentBean.class, params, new com.android.volley.Response.Listener<CateContentBean>() {
            @Override
            public void onResponse(CateContentBean response) {

                if (response.isSuccess()) {
                    Message message = new Message();
                    message.what = 3;
                    message.obj = response.getData();
                    mHandler.sendMessage(message);
                } else {
                    showToast(response.getMsg());
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("result=====", error + "");
            }
        });

        WgzxApplication.addRequest(gsonRequest, Constans.reqTag);
    }


    private void httpUpload(String url) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("uid", getCache().getAsString(keyUid));
        map.put("dep_id", mdepId);
        map.put("cat_id", mcatId);
        map.put("ci_id", mciId);
        map.put("cis_id", mcisId);
        map.put("source", "5");
        map.put("task_address", et_address.getText().toString());
        map.put("task_date", mtimeStamp + "");
        map.put("task_name", et_name.getText().toString());
        map.put("task_phone", et_phone.getText().toString());
        map.put("task_point", mLongi + "," + mLati);
        map.put("task_detail", et_note.getText().toString());
//        map.put("pai_id","");
//        map.put("outTime","");


        Map<String, String> file = new HashMap<String, String>();
        for (int i = 1; i <= totalImages.size(); i++) {

            file.put("myFile" + i, totalImages.get(i - 1));
        }

        if (videoPath != null)
            file.put("myVideo", videoPath);

        //构建请求
        final Request request = new Request.Builder()
                .url(url)//地址
                .post(new OkHttpPicManager().getBody(map, file))//添加请求体
                .build();

        //        发送异步请求，同步会报错，Android4.0以后禁止在主线程中进行耗时操作

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

                showToast("上传失败");

            }

            @Override
            public void onResponse(Response response) {

                try {


//                    Log.d("error=========",response.body().string());
                    JSONObject object = new JSONObject(response.body().string());
                    if (object.getString("code").equals("0")) {
                        setResult(RESULT_OK);
                        finish();

                        Looper.prepare();
                        Toast.makeText(DiseaseUploadActivity.this, "成功", Toast.LENGTH_SHORT).show();
                        Looper.loop();

                    } else {
                        Looper.prepare();
                        Toast.makeText(DiseaseUploadActivity.this, object.getString("msg"), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                    Looper.prepare();
                    showToast("上传失败");
                    Looper.loop();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void sendVideo(String fileName) {

        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(FileUtil.getCacheFilePath(fileName), MediaStore.Images.Thumbnails.MINI_KIND);
        iv_video.setImageBitmap(thumb);
        videoPath = FileUtil.getCacheFilePath(fileName);

        videoView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBackPressed() {
        new MaterialDialog.Builder(DiseaseUploadActivity.this)
                .content("是否放弃上传？")
                .negativeText("取消")
                .positiveText("确定")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        finish();
                    }
                })
                .show();
    }
}
